package com.weijun.keepalive.service

import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import com.weijun.keepalive.CLICK_NOTIFICATION
import com.weijun.keepalive.NOTIFY_LEVEL
import com.weijun.keepalive.logE
import com.weijun.keepalive.receiver.NotificationClickReceiver
import com.weijun.keepalive.utils.createNotification

/**
 * @author: weijun
 * date: 2023/7/5
 * description: 隐藏前台服务通知
 * https://xiaozhuanlan.com/topic/3417586920
 */
internal class HideForegroundService : Service(){

    private val mHandler by lazy(LazyThreadSafetyMode.NONE) { Handler(Looper.getMainLooper()) }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        "HideForegroundService onStartCommand".logE()
        startForeground()
        mHandler.postDelayed({
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                stopForeground(STOP_FOREGROUND_REMOVE)
            }else {
                stopForeground(false)
            }
            stopSelf()
        },2000)
        return START_NOT_STICKY
    }

    private fun startForeground(){
        startForeground(NOTIFY_LEVEL, createNotification(
            Intent(applicationContext, NotificationClickReceiver::class.java).apply {
                action = CLICK_NOTIFICATION
            }
        ))
    }

    override fun onBind(intent: Intent?): IBinder? = null
}